package com.platform.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.platform.annotation.RequestBean;
import com.platform.base.PageUtil;
import com.platform.base.R;
import com.platform.base.mvc.BaseController;
import com.platform.dto.Dept;
import com.platform.dto.User;
import com.platform.logger.annotation.ApiLog;
import com.platform.service.IDept;
import com.platform.service.IUser;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;


/**
 * 
 * <p> Title:Bmxx Mapper</p>
 * <p> Description:  部门信息</p>
 * <p> Copyright: Copyright (c) 2019 </p>
 * <p> Company: </p>
 *
 * @author wys
 * @version 1.0
 */
@Controller
@RequestMapping("/dept") 
@Api(tags="OMS-组织机构模块")
public class DeptController extends BaseController{
	
	@Autowired
    private IDept services;
	@Autowired
	private IUser userServices;
    
    @RequestMapping(value="data",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="分页查询")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "dto", value = "实体对象", required = true, dataType = "Dept"),
        @ApiImplicitParam(name = "start", value = "起始页", required = true, dataType = "int"),
        @ApiImplicitParam(name = "limit", value = "页面显示条数", required = true, dataType = "int")
	})
    public Object selectAll(@RequestBean Dept dto,Integer start,Integer limit,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        PageUtil pageUt = new PageUtil(); 
        pageUt.setPageIndex(start);
        pageUt.setPageSize(limit);
        pageUt.setParams(BeanUtil.beanToMap(dto));
        List<Dept> servicesList = services.selectByPaging(pageUt);
        Integer total = pageUt.getTotal();
        return R.success(servicesList, total);
    }
    @ApiOperation(value="组织机构", notes="组织机构分层处理")
    @RequestMapping(value="v2/orgs", method=RequestMethod.GET)
    @ResponseBody
    public Object getAllOrgs(String areaCode,String keyWord) {
    	return services.getAllOrgs(areaCode, keyWord);
    }
    
    @RequestMapping(value="findUpAndDownByCode",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="查询下级")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "code", value = "编号", required = true, dataType = "String")
	})
    public Object findDeptUpAndDownByCode(String code){
    	return services.findDeptUpAndDownByCode(code);
    }
    
    @ApiLog(value="组织机构（部门）数据删除",desc="组织机构（部门）数据删除")
    @SuppressWarnings("all")
    @RequestMapping(value="delete",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="删除数据")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "ids", value = "多个逗号(,)分隔", required = true, dataType = "String")
	})
    public Object delete(String ids,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) throws IOException {
    	String[] removes = ids.split(",");
    	for(int i=0;i<removes.length;i++) {
    		Dept dept = services.get(removes[i]);
    		services.delete(dept);
    	}
		return R.success();
    }
    
    @ApiLog(value="组织机构（部门）数据保存",desc="组织机构（部门）数据保存")
    @RequestMapping(value="save",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="新增数据")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "dto", value = "实体对象", required = true, dataType = "Dept")
	})
    public Object insert(@Valid Dept dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	dto.setCreateDate(new Date(System.currentTimeMillis()));
    	dto.setCreater(getName());
    	if(services.insert(dto)){
    		return R.success();
    	}else{
    		return R.fail();
    	}
    }
    
    @ApiLog(value="组织机构（部门）数据修改",desc="组织机构（部门）数据修改")
    @RequestMapping(value="edit",method=RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value="修改数据")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "dto", value = "实体对象", required = true, dataType = "Dept")
	})
    public Object update(@Valid Dept dto,HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
    	dto.setLastModifier(getName());
    	dto.setLastModifyDate(new Date(System.currentTimeMillis()));
    	if(services.update(dto)){
        	return R.success();
    	}else{
    		return R.fail();
    	}
    }
    
    @RequestMapping(value="find",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="查询单个数据")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "code", value = "数据编号", required = true, dataType = "String")
	})
    public Object get(String code, HttpServletRequest request, HttpServletResponse response,
            HttpSession session) {
        return services.get(code);
    }
    
    @RequestMapping(value="deptTree",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="查询所有数据返回数据本身")
    public Object deptTree(){
    	return services.getDeptTree();
    }
    
    @RequestMapping(value="deptTreeAndUser",method=RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value="查询所有数据返回数据本身")
    public Object deptTreeAndUser(){
    	List<Dept> deptList = null;
    	Map<String,Object> searchParentMap = MapUtil.newHashMap();
    	searchParentMap.put("deptsuper", -1);
    	deptList = services.selectAll(searchParentMap);
    	treeBuildAndUser(deptList);
    	Map<String,Object> resultJSON = MapUtil.newHashMap();
    	resultJSON.put("name", "Root");
    	resultJSON.put("children", deptList);
    	return resultJSON;
    }
    
    @SuppressWarnings("unlikely-arg-type")
	public void treeBuildAndUser(List<Dept> depts){
    	List<Dept> deptList = new ArrayList<Dept>();
    	for(Dept d : depts){
    		Map<String,Object> childrenMap = MapUtil.newHashMap();
    		childrenMap.put("deptsuper", d.getId());
    		childrenMap.put("name", d.getDeptname());
    		d.setName(d.getDeptname());
    		List<Dept> children = services.selectAll(childrenMap);
    		if(children != null && children.size() > 0){
    			treeBuildAndUser(children);
    		}else{
    			
    			Map<String,Object> userSearchMap = MapUtil.newHashMap();
    			userSearchMap.put("deptcode", d.getId());
    			List<User> users = userServices.selectAll(userSearchMap);
    			if(users.size()==0) {
    				d.setLeaf(true); 
        			if(d.getDeptsuper().equals(0)){
        				deptList.add(d);
        			}
    			}else {
    				List<Dept> uDepts= new ArrayList<>();
    				for(User u : users) {
    					Dept deptU = new Dept();
    					deptU.setId(u.getId());
    					deptU.setName(u.getRealname());
    					deptU.setLeaf(true);
    					uDepts.add(deptU);
    				}
    				d.setChildren(uDepts);
    			}
    			continue;
    		}
    		d.setChildren(children);
    	}
    	depts.removeAll(deptList);
    }
}
